import {Component, OnInit, Injector, ViewChild} from '@angular/core';
import {NzTableHelper} from '@shared/helpers/NzTableHelper';
import {AppComponentBase} from '@shared/common/app-component-base';
import {ServiceProxy} from '@shared/service-proxy/service-proxies';
import {finalize} from 'rxjs/operators';
import { LockLastAddressModalComponent } from '../lock-last-address-modal/lock-last-address-modal.component';

@Component({
  selector: 'app-electronic-lock',
  templateUrl: './electronic-lock.component.html',
  styleUrls: ['./electronic-lock.component.less']
})
export class ElectronicLockComponent extends AppComponentBase implements OnInit {
  @ViewChild('lockAddressModal') lockAddressModal: LockLastAddressModalComponent;
  tableHelper: NzTableHelper;

  keyword: string;
  statistics: any;

  isVisible = false;

  constructor(
    injector: Injector,
    private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  ngOnInit() {
    this.load();
    this.getStatistics();
    this.statistics = { unAllot: "", inTransit: "", totalCount: "", siteName: "" };
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();

  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.getPageElectronicLocksUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.keyword
    ).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }

  getStatistics() {
    this._service.findElectronicLockStatisticsUsingGET().subscribe(result => {
      this.statistics = result.result;
    })
  }

  reset() {
    this.keyword = undefined;
    this.load();
  }

  showAddress(lockNo:string) {
    this.lockAddressModal.show(lockNo);
  }

  handleOk(): void {
    this.isVisible = false;
  }

  handleCancel(): void {
    this.isVisible = false;
  }

}
